<%@page
	import="com.gadglet.core.RequestException,com.gadglet.data.*,com.gadglet.data.utils.*,com.gadglet.params.*,javax.jdo.PersistenceManager,com.google.appengine.api.users.*,com.gadglet.data.utils.PMF,com.gadglet.util.*,com.gadglet.util.UrlUtils,java.util.*,javax.jdo.Query,java.util.logging.Logger"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/static/pageStyle.css"
	title="pageStyle" media="screen,projection" />
<title>Gadglet v0.3  - Registration</title>
</head>
<body>
<div id="content">
<p>
<%
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	String openIDLocation = SharedConstants.googleOpenID;
	
	String thisURL = request.getRequestURI();
	Logger log = Logger.getLogger("register");
	Set<String> attributes = new HashSet();

	String token = null;
	RegistrationToken regToken = null;
	ServletContext context = getServletContext(); 
	String domainName =  null;
	String registrationMethod = null;
	boolean userChangedId = false;
	
	try
	{
		context  = getServletContext();
		domainName = context.getInitParameter(SharedConstants.ctxParamServingDomain);
		registrationMethod = context.getInitParameter(SharedConstants.ctxParamRegMethod);
	}
	catch (Exception e){
		log.warning(e.getMessage());
	}
	
	token = request.getParameter(SharedConstants.registrationTokenParamName);
	
	if (token == null)
		token = (String) session.getAttribute(SharedConstants.registrationTokenParamName);
	
			
	// check for token 
	if (token != null)
		regToken = RegistrationTokenUtils.getTokenById(token);
	
	
	
	if(regToken==null){
		log.warning("token was not found");
		%><%@include file="/secure/messages/registrationProblem.jsp"%><%
	}
	else if(!regToken.isTokenReady() && registrationMethod!=null && registrationMethod.equalsIgnoreCase(SharedConstants.registrationMethodDual))
	{
		log.warning("token is not ready");
		%><%@include file="/secure/messages/registrationProblem.jsp"%><%
	}
	else
	{
		// token exists
	
		session.setAttribute(SharedConstants.registrationTokenParamName, token);
	
		if (user == null) 
		{
			
			if((domainName!=null && !domainName.equals("*")))
				response.sendRedirect(userService.createLoginURL(
						thisURL,
						null,
						openIDLocation + domainName,
						attributes));
			else if (request.getParameter("userdomain") != null) {
				//log.warning(userService.createLoginURL(UrlUtils.getHomeUrl(request),null,openIDLocation+request.getParameter("userdomain"),attributes));
				response.sendRedirect(userService.createLoginURL(
						thisURL,
						null,
						openIDLocation + request.getParameter("userdomain"),
						attributes));
			}
			else 
			{
				%><%@include file="/secure/messages/registrationMsg.jsp"%><%
			}
		} 
		else 
		{
			
			/*check if a valid Google apps gomain
			*https://www.google.com/a/abc.com/o8/ud?be=o8
			*/
			String googleAppsBaseAuthDomain = "https://www.google.com/a/";
			// Gmail or other providers 
			if(!user.getAuthDomain().startsWith(googleAppsBaseAuthDomain) || user.getAuthDomain().length()< googleAppsBaseAuthDomain.length() )
					response.sendRedirect(UrlUtils.getHomeUrl(request, true, false)
						+ "/secure/logoutRegister.jsp");
			
			// restricted domain NOT multi tenant
			if(!domainName.equalsIgnoreCase("*") && !user.getAuthDomain().startsWith(googleAppsBaseAuthDomain+"/a/"+domainName) )
				response.sendRedirect(UrlUtils.getHomeUrl(request, true, false)
						+ "/secure/logoutRegister.jsp");
			
			//check if user was created
			DomainUser domainUser = DomainUserUtils.getMyDomainUserWithOpenID();
	
			DomainAccount domainAccount = DomainAccountUtils
					.getDomainAccountByAuthDomain(user.getAuthDomain());
	
			if (request.getParameter("timezone") == null && domainUser == null)
			{
				%><%@include file="/secure/messages/registrationForm.jsp"%><%
			} 
			else if	(domainAccount == null) 
			{// no domain yet
				if (request.getParameter("timezone") != null)
					session.setAttribute("timezone",request.getParameter("timezone"));
					response.sendRedirect(UrlUtils.getHomeUrl(request, true,false) + "/secure/addDomain.jsp");
				} // domain exists user not exists
				else if (domainUser == null && domainAccount != null) 
				{
					if (token == null)
						token = (String) session.getAttribute(SharedConstants.registrationTokenParamName);
					// load token info
					if (token != null)
						regToken = RegistrationTokenUtils.getTokenById(token);
					// registration
					
					try{
					domainUser = DomainUserUtils.addDomainUserUsingOpenId(user,domainAccount, request.getParameter("timezone"),
					regToken, registrationMethod );
					}
					catch ( RequestException e)
					{
						if(e.getCustomError().equals("userChangedIdOnRegistration"))
							userChangedId = true;
					}
					catch (Exception e){log.warning(e.getMessage());}

					// try to activate
					if (domainUser != null) 
					{
						if (domainAccount.isAllowUsersSelfActivation()
						&& domainAccount.getDomainActiveUsersNum() < domainAccount
								.getMaxUsers()) 
						{
							domainUser.changeStatus(DomainUserStatus.ACTIVE);
							%><%@include file="/secure/messages/registrationComplete.jsp"%><%
						} 
						else
						{
							//TODO: need to build mail messages system.
							%><%@include file="/secure/messages/needsActivation.jsp"%><%
						}

					}
					else if(userChangedId){
						%><%@include file="/secure/messages/notGoogleApps.jsp"%><%
					}
					else
					{
						log.warning("user was not created");
					%><%@include file="/secure/messages/registrationProblem.jsp"%><%
					}

		} 
		else if (domainUser != null && domainAccount != null){
			%><%@include file="/secure/messages/registrationComplete.jsp"%><%
		}
	}
}
%>
</p>
</div>
</body>
</html>

